package com.intersult.nutils.net.traffic;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import com.intersult.nutils.net.Server;
import com.intersult.nutils.schedule.Executor;

/**
 * @author Dieter Kaeppel
 * @date   16.11.2011
 */
public class TrafficProxy extends Server {
	private TrafficConfig config;
	private String connectHost;
	private int connectPort;
	
	public TrafficProxy(InetAddress bindAddress, int port, TrafficConfig config) {
		super(bindAddress, port);
		this.config = config;
	}

	public String getConnectHost() {
		return connectHost;
	}
	public void setConnectHost(String connectHost) {
		this.connectHost = connectHost;
	}
	
	public int getConnectPort() {
		return connectPort;
	}
	public void setConnectPort(int connectPort) {
		this.connectPort = connectPort;
	}
	
	@Override
	public void service(Socket incoming) throws IOException {
		Socket outgoing = null;
		try {
			outgoing = new Socket(connectHost, connectPort);
			Executor.getService().execute(
				new TrafficStreamer(outgoing.getInputStream(), incoming.getOutputStream(), config));
			Executor.getService().execute(
				new TrafficStreamer(incoming.getInputStream(), outgoing.getOutputStream(), config));
		} finally {
			if (outgoing != null)
				outgoing.close();
		}
	}
	
	public static void main(String[] args) {
		if (args.length != 5) {
			System.err.println("Usage: traffic-proxy <listen-port> <connect-host:connect-port> <connection-delay> <max-package-length> <package-delay>");
			System.err.println("    all time parameters are in ms (1/1000 s)");
			System.err.println("    by Dieter Kaeppel");
			System.err.println();
			System.err.println("Example: traffic-proxy 80 localhost:8080 500 128 10");
			System.exit(20);
		}
		TrafficConfig config = new TrafficConfig();
		config.setConnectionDelay(Integer.parseInt(args[2]));
		config.setMaxpackageLength(Integer.parseInt(args[3]));
		config.setPackageDelay(Long.parseLong(args[4]));
		config.setDebug(false);
		TrafficProxy server = new TrafficProxy(null, Integer.parseInt(args[0]), config);
		String[] connect = args[1].split(":");
		server.setConnectHost(connect[0]);
		server.setConnectPort(Integer.parseInt(connect[1]));
		server.run();
	}
}